<template>
	<jb-crud-page ref="pageRef" :searchUrl="pageUrl" :conditions-align="'start'" :searchConditions="pageConditions"
		:editComponent="Edit" @afterSearch="handleAfterSearch" @afterRender="handleAfterRender">
		<template #conditions-form>
			<jb-input v-model:value="pageConditions.keywords" placeholder="请输入名称" clearable />
		</template>
		<template #default="{list,tableStartIndex}">

			<n-layout has-sider>
				<n-layout>

					<jb-table v-if="showTable" ref="tableRef" :row-config="{keyField: 'id', isHover: true}"
						:checkbox-config="{ trigger: 'row',checkRowKeys:selectList.map(item=>item.id) }"
						@checkbox-all="selectAllChangeEvent" @checkbox-change="selectChangeEvent" :data="list"
						:start-index="tableStartIndex">
						<jb-column type="checkbox" width="60" fixed="left"></jb-column>
						<jb-column type="seq" title="序号" width="60" fixed="left"></jb-column>
						<jb-column field="sn" title="编号" min-width="160" fixed="left"></jb-column>
						<jb-column field="briefInfo" title="Function描述" min-width="160"></jb-column>
						<jb-column field="serviceMethod" title="Service方法" min-width="300"></jb-column>
					</jb-table>
				</n-layout>
				<n-layout-sider bordered collapse-mode="width" :collapsed-width="0" :width="300"
					show-trigger="arrow-circle" content-style="padding: 16px;">
					<div class="selected-items-container">
						<div class="selected-header">
							<span>已选择 {{ selectList.length }} 项</span>
						</div>
						<div class="selected-content">
							<template v-if="selectList.length">
								<div v-for="item in selectList" :key="item.id" class="selected-item">
									<span class="item-text">{{ item.sn }}{{item.briefInfo || item.name}}</span>
									<n-button circle size="tiny" type="error" class="delete-btn"
										@click="handleRemoveItem(item)">
										<template #icon>
											<n-icon>
												<close />
											</n-icon>
										</template>
									</n-button>
								</div>
							</template>
							<div v-else class="empty-text">
								暂无选中项
							</div>
						</div>
					</div>
				</n-layout-sider>
			</n-layout>

		</template>
	</jb-crud-page>
</template>

<script setup>
	import {
		useResetableData
	} from "@/hooks/common/use-resetable-data.js";
	import Edit from "./cpns/edit.vue"
	import {
		onMounted,
		ref
	} from "vue";
	import {
		Close
	} from '@vicons/ionicons5'
	import {
		JBoltApi
	} from "@/service/request/index.js";

	const props = defineProps({
		appId: String
	})

	const pageRef = ref(null)
	const pageUrl = ref('')
	const pageConditions = useResetableData({
		keywords: '',
		enabled: true
	})

	const tableRef = ref(null)

	const selectList = ref([])


	// 单选事件处理
	function selectChangeEvent({
		row,
		checked
	}) {
		if (checked) {
			if (!selectList.value.some(item => item.id === row.id)) {
				selectList.value.push(row);
			}
		} else {
			selectList.value = selectList.value.filter(item => item.id !== row.id);
		}
	}

	const selectAllChangeEvent = ({
		checked
	}) => {
		const $table = tableRef.value;
		if ($table) {
			const records = $table.getCheckboxRecords();
			if (checked) {
				// 全选时，将所有记录添加到 selectList 中，并去重
				const existingIds = new Set(selectList.value.map(item => item.id));
				const newRecords = records.filter(record => !existingIds.has(record.id));
				selectList.value = [...selectList.value, ...newRecords];
			} else {
				// 反选时，移除所有记录
				const recordIds = new Set(resultList.value.map(record => record.id));
				selectList.value = selectList.value.filter(item => !recordIds.has(item.id));
			}
			console.log(checked ? '所有勾选事件' : '所有取消事件', records);
			console.log('手动', selectList.value);
		}
	}

	const resultList = ref([])

	function handleAfterSearch(list) {
		resultList.value = list
	}

	function handleAfterRender(list) {
		const $table = tableRef.value
		if ($table) {
			$table.setCheckboxRow(selectList.value, true)
		}
	}

	function handleRemoveItem(item) {
		// 从选中列表中移除
		selectList.value = selectList.value.filter(i => i.id !== item.id)

		// 取消表格中对应行的选中状态
		const $table = tableRef.value
		if ($table) {
			$table.setCheckboxRow([item], false)
		}
	}


	const submit = async (callback) => {
		if (selectList.value.length > 0) {
			await JBoltApi.post('/aiApp/submitFunction', {
				appId: props.appId,
				list: selectList.value.map(item => item.id)
			})

			if (callback) {
				callback()
			}
			return true
		}
	}

	defineExpose({
		submit
	})
	let showTable = ref(false)

	function loadSelectedList() {
		JBoltApi.get('/aiApp/getFuncByAppId', {
			appId: props.appId
		}).then(res => {
			console.log(res.result.data);
			if (res.result.data != null) {

				selectList.value = res.result.data.map(item => {
					return {
						name: item.value,
						id: item.key
					}
				})
			}

			showTable.value = true
			pageUrl.value = '/aiFunction/list'
		})
	}

	onMounted(() => {
		if (props.appId) {
			loadSelectedList()
		}
	})
</script>


<style scoped>
	.selected-items-container {
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.selected-header {
		padding: 8px 0;
		font-weight: 500;
		border-bottom: 1px solid var(--n-border-color);
		margin-bottom: 12px;
	}

	.selected-content {
		flex: 1;
		overflow-y: auto;
	}

	.selected-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 8px 12px;
		margin-bottom: 8px;
		border-radius: 4px;
		background-color: var(--n-card-color);
		transition: all 0.3s;
	}

	.selected-item:hover {
		background-color: var(--n-table-header-color);
	}

	.item-text {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		margin-right: 8px;
	}

	.delete-btn {
		opacity: 0.8;
	}

	.delete-btn:hover {
		opacity: 1;
	}

	.empty-text {
		text-align: center;
		color: var(--n-text-color-disabled);
		padding: 32px 0;
	}
</style>